$(document).ready(function() {
    let investmentGoals = [];
    let portfolios = [];
    let totalPages = 1;
    let currentPage = 1;
    let itemsPerPage = 10;

    // 自定义alert函数
    function customAlert(message) {
        $('#customAlertMessage').text(message);
        $('#customAlertModal').modal('show');
    }

    // 获取所有投资组合用于下拉列表
    function fetchPortfolios() {
        $.ajax({
            url: `/api/portfolios/getAllPortfolios`,
            type: 'GET',
            success: function(data) {
                portfolios = data;
                renderPortfolioSelects();
                renderSearchPortfolioSelect();
            },
            error: function(xhr, status, error) {
                console.error('Error fetching portfolios:', error);
            }
        });
    }

    function renderPortfolioSelects() {
        const addSelect = $('#addPortfolioId');
        const editSelect = $('#editPortfolioId');
        
        addSelect.empty();
        editSelect.empty();
        
        addSelect.append('<option value="">请选择</option>');
        editSelect.append('<option value="">请选择</option>');
        
        portfolios.forEach(portfolio => {
            addSelect.append(`<option value="${portfolio.id}">${portfolio.portfolioName}</option>`);
            editSelect.append(`<option value="${portfolio.id}">${portfolio.portfolioName}</option>`);
        });
    }

    function renderSearchPortfolioSelect() {
        const searchSelect = $('#searchPortfolioId');
        searchSelect.empty();
        searchSelect.append('<option value="">全部投资组合</option>');
        
        portfolios.forEach(portfolio => {
            searchSelect.append(`<option value="${portfolio.id}">${portfolio.portfolioName}</option>`);
        });
    }

    function fetchInvestmentGoals() {
        const portfolioId = $('#searchPortfolioId').val();
        const goalType = $('#searchGoalType').val();
        const achieved = $('#searchAchieved').val();
        itemsPerPage = parseInt($('#itemsPerPage').val(), 10);
        const queryParams = {
            portfolioId: portfolioId || '',
            goalType: goalType || '',
            achieved: achieved || '',
            pageNo: currentPage,
            pageSize: itemsPerPage
        };

        $.ajax({
            url: `/api/investmentGoals/getInvestmentGoalsByConditions`,
            type: 'GET',
            data: queryParams,
            success: function(data) {
                if (!data || !data.records) {
                    console.error('Invalid data received:', data);
                    customAlert('获取数据失败，请检查输入条件或稍后重试。');
                    return;
                }

                investmentGoals = data.records;
                totalPages = data.pages;
                renderInvestmentGoalTable(investmentGoals);
                updatePagination();
            },
            error: function(xhr, status, error) {
                console.error('Error fetching investment goals:', error);
                customAlert('获取数据失败，请检查网络连接或稍后重试。');
            }
        });
    }

    function renderInvestmentGoalTable(data) {
        const investmentGoalTableBody = $('#investmentGoalTableBody');
        investmentGoalTableBody.empty();

        if (data.length > 0) {
            data.forEach(goal => {
                // 获取投资组合名称
                let portfolioName = '';
                if (goal.portfolioId) {
                    const portfolio = portfolios.find(p => p.id == goal.portfolioId);
                    if (portfolio) {
                        portfolioName = portfolio.portfolioName;
                    }
                }

                const tr = $('<tr>');
                tr.append($('<td>').text(portfolioName));
                tr.append($('<td>').text(goal.goalTypeName));
                tr.append($('<td>').text(goal.targetValue));
                // 显示当前值（投资组合的收益率）
                const currentValueText = goal.currentValue !== null ? goal.currentValue.toFixed(2) + '%' : '';
                tr.append($('<td>').text(currentValueText));
                tr.append($('<td>').text(goal.achievedName));
                tr.append($('<td>').text(goal.targetDate || ''));
                
                const actionsTd = $('<td>');
                actionsTd.html(`
                    <button class="btn btn-sm btn-warning me-2" onclick="editInvestmentGoal(${goal.id})">编辑</button>
                    <button class="btn btn-sm btn-danger" onclick="deleteInvestmentGoal(${goal.id})">删除</button>
                `);
                tr.append(actionsTd);
                investmentGoalTableBody.append(tr);
            });
        } else {
            investmentGoalTableBody.html('<tr><td colspan="7" class="text-center">暂无数据</td></tr>');
        }
    }

    // 更新分页控件
    function updatePagination() {
        // 更新页码显示
        $('#currentPage').text(currentPage);
        $('#totalPages').text(totalPages);
        
        // 更新上一页和下一页按钮状态
        if (currentPage <= 1) {
            $('#prevPage').addClass('disabled');
        } else {
            $('#prevPage').removeClass('disabled');
        }
        
        if (currentPage >= totalPages) {
            $('#nextPage').addClass('disabled');
        } else {
            $('#nextPage').removeClass('disabled');
        }
    }

    function handleSizeChange(newSize) {
        itemsPerPage = newSize;
        currentPage = 1; // 重置到第一页
        fetchInvestmentGoals();
    }

    function handleCurrentChange(newPage) {
        // 确保页码在有效范围内
        if (newPage < 1) newPage = 1;
        if (newPage > totalPages) newPage = totalPages;
        
        if (newPage !== currentPage) {
            currentPage = newPage;
            fetchInvestmentGoals();
        }
    }

    function addNewInvestmentGoal() {
        const portfolioId = $('#addPortfolioId').val();
        const goalType = $('#addGoalType').val();
        const targetValue = $('#addTargetValue').val();
        const targetDate = $('#addTargetDate').val();

        if (!portfolioId) {
            customAlert('请选择投资组合');
            return;
        }

        if (goalType === '') {
            customAlert('目标类型不能为空');
            return;
        }

        if (targetValue.trim() === '' || parseFloat(targetValue) <= 0) {
            customAlert('目标值必须大于0');
            return;
        }

        const newInvestmentGoal = {
            portfolioId: portfolioId,
            goalType: goalType,
            targetValue: targetValue,
            targetDate: targetDate || null
        };

        $.ajax({
            url: `/api/investmentGoals/addInvestmentGoal`,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(newInvestmentGoal),
            success: function(data) {
                $('#addInvestmentGoalForm')[0].reset();
                $('#addInvestmentGoalModal').modal('hide');
                fetchInvestmentGoals();
                customAlert('新增成功');
            },
            error: function(xhr, status, error) {
                console.error('Error adding investment goal:', error);
                customAlert('新增投资目标失败');
            }
        });
    }

    function saveEditInvestmentGoal() {
        const investmentGoalId = $('#editInvestmentGoalId').val();
        const portfolioId = $('#editPortfolioId').val();
        const goalType = $('#editGoalType').val();
        const targetValue = $('#editTargetValue').val();
        const currentValue = $('#editCurrentValue').val();
        const achieved = $('#editAchieved').val();
        const targetDate = $('#editTargetDate').val();

        if (!portfolioId) {
            customAlert('请选择投资组合');
            return;
        }

        if (goalType === '') {
            customAlert('目标类型不能为空');
            return;
        }

        if (targetValue.trim() === '' || parseFloat(targetValue) <= 0) {
            customAlert('目标值必须大于0');
            return;
        }

        const updatedInvestmentGoal = {
            id: investmentGoalId,
            portfolioId: portfolioId,
            goalType: goalType,
            targetValue: targetValue,
            currentValue: currentValue || null,
            achieved: achieved,
            targetDate: targetDate || null
        };

        $.ajax({
            url: `/api/investmentGoals/updateInvestmentGoal`,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(updatedInvestmentGoal),
            success: function(data) {
                $('#editInvestmentGoalModal').modal('hide');
                fetchInvestmentGoals();
                customAlert('信息更新成功');
            },
            error: function(xhr, status, error) {
                console.error('Error updating investment goal:', error);
                customAlert('更新投资目标失败');
            }
        });
    }

    function deleteInvestmentGoal(id) {
        if (confirm('确定要删除该投资目标吗？')) {
            $.ajax({
                url: `/api/investmentGoals/deleteInvestmentGoal/${id}`,
                type: 'POST',
                success: function() {
                    fetchInvestmentGoals();
                    customAlert('删除成功');
                },
                error: function(xhr, status, error) {
                    console.error('Error deleting investment goal:', error);
                    customAlert('删除投资目标失败');
                }
            });
        }
    }

    // 全局函数供HTML调用
    window.editInvestmentGoal = function(id) {
        const goal = investmentGoals.find(p => p.id == id);
        if (goal) {
            $('#editInvestmentGoalId').val(goal.id);
            $('#editPortfolioId').val(goal.portfolioId || '');
            $('#editGoalType').val(goal.goalType);
            $('#editTargetValue').val(goal.targetValue);
            // 显示当前值（投资组合的收益率）
            const currentValueText = goal.currentValue !== null ? goal.currentValue : '';
            $('#editCurrentValue').val(currentValueText);
            $('#editAchieved').val(goal.achieved);
            $('#editTargetDate').val(goal.targetDate || '');
            $('#editInvestmentGoalModal').modal('show');
        }
    };

    window.deleteInvestmentGoal = deleteInvestmentGoal;

    // 事件绑定
    $('#fetchInvestmentGoalsButton').on('click', fetchInvestmentGoals);
    $('#saveAddInvestmentGoal').on('click', addNewInvestmentGoal);
    $('#saveEditInvestmentGoal').on('click', saveEditInvestmentGoal);

    $('#itemsPerPage').on('change', function() {
        handleSizeChange(parseInt($(this).val(), 10));
    });

    $('#pPage').on('click', function(e) { 
        e.preventDefault();
        if (currentPage > 1) {
            handleCurrentChange(currentPage - 1); 
        }
    });
    
    $('#nPage').on('click', function(e) { 
        e.preventDefault();
        if (currentPage < totalPages) {
            handleCurrentChange(currentPage + 1); 
        }
    });

    // 初始化
    fetchPortfolios();
    fetchInvestmentGoals();
});